package cn.ug.msg.mq;

import cn.ug.bean.base.SerializeObject;
import cn.ug.bean.type.ResultType;
import cn.ug.core.ensure.Ensure;
import cn.ug.feign.MemberUserService;
import cn.ug.member.bean.response.MemberUserBean;
import cn.ug.msg.bean.status.CommonConstants;
import cn.ug.msg.service.MsgService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import static cn.ug.config.QueueName.QUEUE_MSG_SEND;


/**
 * 消息管理(1.短信 2.站内信)
 * @auther ywl
 */
@Component
@RabbitListener(queues = QUEUE_MSG_SEND)
public class MsgReceiver {

    private Log log = LogFactory.getLog(MsgReceiver.class);

    @Resource
    private MsgService msgService;

    @Resource
    private MemberUserService memberUserService;

    private ObjectMapper mapper = new ObjectMapper();



    @RabbitHandler
    public void process(Msg msg) {
        try {

            log.info("-----消息发送开始------");
            log.info(mapper.writeValueAsString(msg));

            //校验参数
            Ensure.that(msg == null).isTrue("00000002");
            Ensure.that(msg.getType()).isNull("19000402");
            Ensure.that(CommonConstants.MsgType.getName(msg.getType())).isNull("19000403");

            //如果会员Id存在获取手机号码
            if(StringUtils.isNotBlank(msg.getMemberId())){
                SerializeObject<MemberUserBean> obj = memberUserService.findById(msg.getMemberId());
                if(obj.getCode() == ResultType.NORMAL) {
                    MemberUserBean memberUserBean = obj.getData();
                    msg.setMobile(memberUserBean.getMobile());  //设置手机号码
                }
            }

            msgService.sendMsg(msg);
            log.info("-----消息发送结束------");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}
